// this is copied from yurzhang
// but changed a little
import { resolve } from "node:path";
import { PluginOption, defineConfig } from "vite";
import packageJson from "./package.json";
var M = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

const tampermonkey = () => {
  var now = new Date()
  var Second = now.getSeconds()
  var Minute = now.getMinutes()
  var Hour = now.getHours()
  var Day = now.getDay()
  var Month = now.getMonth()
  var Year = now.getFullYear()
  M[2] += ((Year % 4 === 0 && Year % 100 !== 0) || Year % 400 === 0) ? 1 : 0
  Day += 37
  if (Hour >= 24) {
    Day++
    Hour = Hour - 24
  }
  while (Day > M[Month]) {
    Day -= M[Month]
    Month++
  }
  if (Month > 12) {
    Year++
    Month = 1
  }
  console.log(`Generated on ${Year}/${Month}/${Day} ${Hour}:${Minute}:${Second} `)
  let headers = `
// ==UserScript==
// @name         ${packageJson.name}
// @version      ${packageJson.version}
`;
  for (let key in packageJson.tampermonkey) {
    let value = packageJson.tampermonkey[key]
    if (typeof value !== 'object') {
      headers = headers + `// @${key}${' '.repeat(13 - key.length)}${value}\n`
    } else {
      for (let v of value) {
        headers = headers + `// @${key}${' '.repeat(13 - key.length)}${v}\n`
      }
    }
  }
  headers = headers + `// ==/UserScript==`
  headers = headers.trim()

  return {
    name: "tampermonkey",
    apply: "build",
    enforce: "post",
    generateBundle: (_options, bundle) => {
      const cssBundle = bundle["style.css"];
      let css = ''
      if (cssBundle && cssBundle.type === "asset") {
        css = `GM_addStyle(\`${cssBundle.source.toString().trim()}\`);\n`;
      }
      const [, target] = Object.entries(bundle)
        .find(([name]) => name.includes("user.js")) ?? [];
      if (!target || target.type !== "chunk") {
        return;
      }

      target.code = `${headers}\n\n${css}${target.code}`;
    },
  } as PluginOption;
};

export default defineConfig({
  plugins: [
    tampermonkey(),
    // vitePluginForArco({ style: 'css' })
  ],
  resolve: {
    alias: {
      "~": resolve(__dirname, "src"),
    },
  },
  build: {
    target: "esnext",
    lib: {
      entry: resolve(__dirname, "src/main.ts"),
      name: "userscript",
      formats: ["es"],
      fileName: (format) => `${packageJson.name}.${format}.user.js`,
    },
    rollupOptions: {
      output: {
        inlineDynamicImports: true,
        compact: true
      }
    },
    minify: "terser",
    terserOptions: {
      mangle: {
        reserved: ["GM"],
      }
    },
  },
  define: {
    "process.env.NODE_ENV": "\"production\"",
  },
  css: {
    modules: {
      localsConvention: "camelCaseOnly",
    },
  },
});
